package com.micro.ai.auth.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.auth.dto.TenantCreateRequest;
import com.micro.ai.auth.dto.TenantDTO;
import com.micro.ai.auth.dto.TenantUpdateRequest;
import com.micro.ai.auth.service.TenantService;
import com.micro.ai.commons.domain.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.micro.ai.auth.annotation.AuditLogAnnotation;
/**
 * 租户管理控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/tenants")
@Tag(name = "租户管理", description = "租户的增删改查等操作")
public class TenantController {

    @Autowired
    private TenantService tenantService;

    /**
     * 创建租户
     */
    @PostMapping
    @PreAuthorize("hasAuthority('tenant:create')")
    @Operation(summary = "创建租户", description = "创建新的租户")
    @AuditLogAnnotation(action = "CREATE", resourceType = "TENANT", description = "创建租户")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功",
            content = @Content(schema = @Schema(implementation = TenantDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误或子域名已存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<TenantDTO> createTenant(@Valid @RequestBody TenantCreateRequest request) {
        log.info("创建租户: name={}, subdomain={}", request.getName(), request.getSubdomain());
        TenantDTO tenant = tenantService.createTenant(request);
        return ApiResponse.success(tenant);
    }

    /**
     * 更新租户
     */
    @PutMapping("/{tenantId}")
    @PreAuthorize("hasAuthority('tenant:update')")
    @Operation(summary = "更新租户", description = "更新指定租户的信息")
    @AuditLogAnnotation(action = "UPDATE", resourceType = "TENANT", description = "更新租户")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功",
            content = @Content(schema = @Schema(implementation = TenantDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "租户不存在")
    })
    public ApiResponse<TenantDTO> updateTenant(
            @Parameter(description = "租户ID", required = true) @PathVariable String tenantId,
            @Valid @RequestBody TenantUpdateRequest request) {
        log.info("更新租户: tenantId={}", tenantId);
        TenantDTO tenant = tenantService.updateTenant(tenantId, request);
        return ApiResponse.success(tenant);
    }

    /**
     * 删除租户
     */
    @DeleteMapping("/{tenantId}")
    @PreAuthorize("hasAuthority('tenant:delete')")
    @Operation(summary = "删除租户", description = "删除指定租户")
    @AuditLogAnnotation(action = "DELETE", resourceType = "TENANT", description = "删除租户")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "租户下存在用户不能删除"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "租户不存在")
    })
    public ApiResponse<Void> deleteTenant(
            @Parameter(description = "租户ID", required = true) @PathVariable String tenantId) {
        log.info("删除租户: tenantId={}", tenantId);
        tenantService.deleteTenant(tenantId);
        return ApiResponse.success();
    }

    /**
     * 获取租户详情
     */
    @GetMapping("/{tenantId}")
    @PreAuthorize("hasAuthority('tenant:view')")
    @Operation(summary = "获取租户详情", description = "根据租户ID获取租户详细信息")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = TenantDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "租户不存在")
    })
    public ApiResponse<TenantDTO> getTenantById(
            @Parameter(description = "租户ID", required = true) @PathVariable String tenantId) {
        TenantDTO tenant = tenantService.getTenantById(tenantId);
        return ApiResponse.success(tenant);
    }

    /**
     * 根据子域名获取租户
     */
    @GetMapping("/subdomain/{subdomain}")
    @Operation(summary = "根据子域名获取租户", description = "根据子域名获取租户信息（公开接口）")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = TenantDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "租户不存在")
    })
    public ApiResponse<TenantDTO> getTenantBySubdomain(
            @Parameter(description = "子域名", required = true, example = "micro-ai") @PathVariable String subdomain) {
        TenantDTO tenant = tenantService.getTenantBySubdomain(subdomain);
        return ApiResponse.success(tenant);
    }

    /**
     * 分页查询租户
     */
    @GetMapping
    @PreAuthorize("hasAuthority('tenant:view')")
    @Operation(summary = "分页查询租户", description = "根据条件分页查询租户列表")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Page<TenantDTO>> listTenants(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "关键词（名称/子域名/邮箱）") @RequestParam(required = false) String keyword,
            @Parameter(description = "状态") @RequestParam(required = false) String status,
            @Parameter(description = "套餐类型") @RequestParam(required = false) String planType) {
        Page<TenantDTO> page = tenantService.listTenants(pageNum, pageSize, keyword, status, planType);
        return ApiResponse.success(page);
    }
}

